package com.changxianggu.crawler.cloud.test;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.changxianggu.cloud.crawler.core.WebApplication;
import com.changxianggu.cloud.crawler.core.modules.storage.entity.CxgBook;
import com.changxianggu.cloud.crawler.core.modules.storage.service.ICxgBookService;
import com.changxianggu.cloud.crawler.core.utils.HttpUtil;
import com.changxianggu.cloud.crawler.core.utils.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {WebApplication.class})// 指定启动类
@Slf4j
public class ZhongCai {

    @Autowired
    ICxgBookService bookService;

    public static final String ORIGIN = "http://lib.zcmedia.cn";
    public static final String REFERER = "http://lib.zcmedia.cn/Book/Search";
    public static final String URL_PRE = "http://lib.zcmedia.cn/AudioVisual/Show?vpath=";

    @Test
    public void initCrawler() throws Exception {
        doCrawler();
    }

    public void doCrawler() throws Exception {
        int pageNum =245;
        int totalPage = 345;
        int pageSize = 8;
        for (int i = pageNum; i <= totalPage; i++) {
            String url = "http://lib.zcmedia.cn/Book/GetList";
            Map<String, Object> parameter = MapUtil.newHashMap(4);
            parameter.put("Page", i);
            parameter.put("Type", 0);
            parameter.put("Size", pageSize);
            parameter.put("Order", "IssueDate desc");
            Map<String, Object> headers = MapUtil.newHashMap(5);
            headers.put("ORIGIN", ORIGIN);
            headers.put("User-Agent", UserAgentUtil.random());
            headers.put("Referer", REFERER);
            String result = HttpUtil.doPost(url, headers, parameter);
            if (StrUtil.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                Boolean errcode = jsonObject.getBoolean("Success");
                if (errcode != null && errcode == true) {
                    JSONArray listObject = jsonObject.getJSONArray("Models");
                    int size = listObject.size();
                    List<CxgBook> listBook = new ArrayList<>();
                    for (int k = 0; k < size; k++) {
                        CxgBook bookEntity = new CxgBook();
                        JSONObject jsonTmp = listObject.getJSONObject(k);
                        bookEntity.setIsSync(0);
                        bookEntity.setCreateTime(LocalDateTime.now());
                        bookEntity.setPressName("中国财政经济出版社");
                        bookEntity.setStatus(1);
                        bookEntity.setPressId(71);
                        bookEntity.setAuthor(jsonTmp.getString("Author"));
                        bookEntity.setBookIsbn(jsonTmp.getString("ISBN").replace("-",""));
                        String pubDateStr = jsonTmp.getString("IssueDate");
                        if (StrUtil.isNotBlank(pubDateStr)) {
                            try {
                                String[] dateArr = pubDateStr.split("-");
                                String month = dateArr[1];
                                String day = dateArr[2];
                                if (Integer.parseInt(dateArr[1])<10) {
                                    month = "0"+ month;
                                }
                                if (Integer.parseInt(dateArr[2])<10) {
                                    day = "0"+ day;
                                }
                                String pubDate = dateArr[0]+ "-" + month + "-" +day+ " 00:00:00";
                                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                LocalDateTime ldt = LocalDateTime.parse(pubDate,df);
                                bookEntity.setPubDate(ldt);
                            }catch (Exception e) {

                            }
                        }
                        bookEntity.setBookName(jsonTmp.getString("Name"));
                        if (StrUtil.isNotBlank(jsonTmp.getString("Sys_Fld_CoverPath"))) {
                            bookEntity.setCover(URL_PRE+jsonTmp.getString("Sys_Fld_CoverPath")+"&vtag=1&ptype=1");
                        }
                        bookEntity.setPkId(jsonObject.getString("Sys_Fld_Doi"));
                        CxgBook tempEntity = getBookEntity(jsonTmp.getString("Sys_Fld_Doi"),bookEntity);
                        listBook.add(tempEntity);
                    }
                    bookService.saveBatch(listBook);
                    log.info("第" + i + "页数据保存成功");
                    log.warn("--->" + i);
                }
            }
        }
    }

    public CxgBook getBookEntity(String numId,CxgBook bookEntity) throws Exception {
        String url = "http://lib.zcmedia.cn/Book/Detail?id="+numId;
        Map<String, Object> headers = MapUtil.newHashMap(5);
        headers.put("User-Agent", UserAgentUtil.random());
        headers.put("Referer", REFERER);
        String result = HttpUtil.doGet(url, headers);
        while (result.contains("页面没有找到")) {
            //睡眠2秒继续访问
            Thread.sleep(2000);
            result = HttpUtil.doPost(url, headers);
        }
        if (StrUtil.isNotBlank(result)) {
            Document htmlDoc = Jsoup.parse(result);
            Element bookContent = htmlDoc.select("body").first();
            if (bookContent != null) {
                bookEntity.setPkId(numId);

                Element digUriElement = bookContent.select(".reading-btn").first();
                if (digUriElement != null) {
                    String digUriStr = digUriElement.attr("href");
                    if (StrUtil.isNotBlank(digUriStr)) {
                        bookEntity.setDigitalUri(ORIGIN+digUriStr);
                    }else {
                        bookEntity.setDigitalUri("无");
                    }
                }

                //catalog
                Element catalogElement = bookContent.select(".book-info-con").first();
                if (catalogElement != null) {
                    String catalogStr = catalogElement.select("a").text();
                    if (StrUtil.isNotBlank(catalogStr)) {
                        bookEntity.setCatalog(catalogStr);
                    }
                }

                //brief
                Element briefElement = bookContent.select(".content-info-con").first();
                if (briefElement != null) {
                    String briefStr = briefElement.text();
                    if (StrUtil.isNotBlank(briefStr)) {
                        bookEntity.setBrief(briefStr);
                    }
                }

                //awards
                Element awardsElement = bookContent.select(".book-det-info h4").first();
                if (awardsElement != null) {
                    String awardsStr = awardsElement.text();
                    if (StrUtil.isNotBlank(awardsStr)) {
                        bookEntity.setAwards(awardsStr);
                    }
                }
            }
        }
        return bookEntity;
    }

    /**
     * 判断一个字符串是否都为数字
     *
     * @param strNum
     * @return
     */
    public boolean isDigit(String strNum) {
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) strNum);
        return matcher.matches();
    }

    /**
     * 截取数字
     *
     * @param content
     * @return
     */
    public String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }
}
